package cn.ac.iscas.dba;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.mongodb.BasicDBObject;

import cn.ac.iscas.dbo.Item;
import cn.ac.iscas.dbo.ItemList;

/**
 * @author Simon@itechs
 *
 */
public class ItemDBA extends BasicDBA{
	public boolean storeItemsDB(ArrayList<Item> items){
		for (int i = 0; i < items.size(); i++){
			Item item = items.get(i);
			BasicDBObject doc = getItemDBO(item);
			this.connection.insert(doc);
		}
		//closeConnection();
		return false;
	}
	
	public boolean storeItemDB(Item item){
		BasicDBObject doc = getItemDBO(item);
		this.connection.insert(doc);
		//closeConnection();
		return true;
	}
	
	private BasicDBObject getItemDBO(Item item){
		BasicDBObject doc = new BasicDBObject();
		if (item == null) return doc;
		BasicDBObject attrs = new BasicDBObject();
		doc.put("name", item.getName());
		doc.put("price", item.getPrice());
		Set set = item.getAttributes().entrySet();        
		Iterator i = set.iterator();
		while(i.hasNext()){
		     Map.Entry<String, Object> entry=(Map.Entry <String, Object>)i.next();
		     String content = (String)entry.getValue();
		     String attrName = (String)entry.getKey();
		     content = content.replaceAll("\\.", "&dot;");
		     attrName = attrName.replaceAll("\\.", "&dot;");
		     String[] tmp = content.split("&nbsp;");
		   //  System.out.println(content);
		     if (tmp.length > 2){
		    	 BasicDBObject tmpdoc = new BasicDBObject();
		    	 for (int j = 1; j < tmp.length; j++){
		    		 tmpdoc.put(tmp[j], true);
		    	 }
		    	 attrs.put(attrName, tmpdoc);
		     } else if (tmp.length == 2){
		    	 attrs.put(attrName, tmp[1]);
		     } else {
		    	 attrs.put(attrName, tmp[0]);
		     }
		}
		doc.put("attributes", attrs);

		return doc;
	}
}
